import { initializeHighlightEventListeners } from "~contents/hoverTools";
import { decodeURIWrapper } from "~utils/common";
import { HIGHLIGHT_CLASS } from "~utils/constants";

const loadImage = (highlightVal) => {
  console.log("loading image highlight...");
  const getImageFileName = (imageSrc) => {
    try {
      if (imageSrc.trimStart().startsWith("data:image")){
        return imageSrc;
      } else {
        const matches = imageSrc.match(/([^/]+?\.(jpg|jpeg|png|svg|gif|webp|ico))/i);
        return matches[1];
      }
    } catch (error) {
      console.error(`image src invalid: ${imageSrc}`);
      return null;
    }
  }

  const highlightImageElem = Array.from(document.getElementsByTagName("img")).filter(item => {
    return getImageFileName(decodeURIWrapper(item.src)) === getImageFileName(decodeURIWrapper(highlightVal.imageSrc));
    // item.src.split("/").slice(-1)[0] === imageFileName
  })[0];

  console.log(`found image element: ${highlightImageElem}`);
  console.log("highlighting image...");
  if (highlightImageElem) {
    highlightImageElem.classList.add(HIGHLIGHT_CLASS);
    highlightImageElem.dataset.highlightId = highlightVal.uuid;
    highlightImageElem.textContent = highlightVal.imageSrc;
    highlightImageElem.setAttribute("viewstate", highlightVal.viewstate);
    // highlightImageElem.setAttribute("decoding", "sync");
    initializeHighlightEventListeners(highlightImageElem);
  }
}

export default loadImage;
